package com.wimcorp.magic.dataloader.costs;

import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONParser;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.wimcorp.magic.data.CostData;
import com.wimcorp.magic.input.CostInput;
import com.wimcorp.magic.input.Location;
import com.wimcorp.magic.input.Type;

public class ReturnCostWidget extends CostWidget {

	private ListBox typeList;
	private ListBox locationList;
	private ListBox destinationList;
	private Grid grid = new Grid(3, 2);

	public ReturnCostWidget(CostInput cost) {
		super(cost);
		typeList = new ListBox();
		locationList = new ListBox();
		destinationList = new ListBox();
		addTypeListBox("Type", typeList, 0);
		addLocationListBox("Location", locationList, 1);
		addLocationListBox("Destination", destinationList, 2);
		getConfigurationPanel().add(grid);
	}

	private void addTypeListBox(String label, ListBox list, int row) {

		grid.setWidget(row, 0, new Label(label));
		for (Type type : Type.values()) {
			list.addItem(type.getName(), type.toString());
		}
		grid.setWidget(row, 1, list);
	}

	private void addLocationListBox(String label, ListBox list, int row) {

		grid.setWidget(row, 0, new Label(label));
		for (Location location : Location.values()) {
			list.addItem(location.getName(), location.toString());
		}
		grid.setWidget(row, 1, list);

	}

	public void load(CostData cost) {
		JSONObject config = (JSONObject) JSONParser.parseLenient(cost.getConfig());
		loadListBox(typeList, config.get("type"));
		loadListBox(locationList, config.get("location"));
		loadListBox(destinationList, config.get("destination"));

	}

	@Override
	public String getConfig() {
		JSONObject config = new JSONObject();
		config.put("type", getSelectedItems(typeList));
		config.put("location", getSelectedItems(locationList));
		config.put("destination", getSelectedItems(destinationList));
		return config.toString();
	}

}
